package com.example.zookeeper.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author LiYuhang
 * @version 0.1
 * @application
 * @Date 2021/9/2 13:36
 */
@RestController
public class ZookeeperController {

     private static final Logger log = LoggerFactory.getLogger(ZookeeperController.class);
    private final CuratorFramework curatorFramework;

    @Autowired
    public ZookeeperController(CuratorFramework curatorFramework) {
        this.curatorFramework = curatorFramework;
    }

    @RequestMapping("/zk/lock")
    public Long save() {
        String name = "myLock";
        // 获取锁
        final InterProcessSemaphoreMutex balanceLock = new InterProcessSemaphoreMutex(curatorFramework,
            "/zktest" + name);
        try {
            // 执行加锁操作
            if (balanceLock.acquire(5, TimeUnit.MILLISECONDS)) {
                log.info("get held :{}", name);
                Thread.sleep(100);
                return System.currentTimeMillis();
            }
        } catch (Exception e) {
            log.error("加锁失败:{}", e.getMessage());
        } finally {
            if (balanceLock.isAcquiredInThisProcess()) {
                try {
                    // 释放锁资源
                    balanceLock.release();
                } catch (Exception e) {
                    log.error("释放锁失败:{}", e.getMessage());
                }
            }
        }
        return 1L;
    }

}
